<template>
  <div class="row q-pb-xs q-px-md full-width">
    <div style="flex: 1">
      <q-input v-model="filter" :placeholder="placeholder" dense standout rounded>
        <template v-slot:append>
          <q-icon v-if="filter !== ''" name="close" @click="filter = ''" class="cursor-pointer" />
          <q-icon name="search" />
        </template>
      </q-input>
    </div>
    <div v-if="!dense" style="min-width: 50px;" class="flex flex-center">
      <q-btn v-if="!consumer" label="登录" unelevated dense color="secondary" @click="toLogin" />
      <div v-else><a class="q-px-sm text-dark">{{ consumer.nickname }}</a><q-btn label="个人中心" size="sm" unelevated dense color="info" to="/shop/profile" /></div>
    </div>
  </div>
</template>

<script>
import { defineComponent, ref } from 'vue';

export default defineComponent({
  name: 'headerBar',
  props: {
    placeholder: {
      type: String,
      default: '搜索 商品...'
    },
    modelValue: String,
    dense: {
      type: Boolean,
      default: false
    }
  },
  emits: ['update:modelValue'],
  data () {
    return {
      filter: '',
      consumer: null
    }
  },
  mounted () {
    // 取消费者信息
    const token = this.$q.localStorage.getItem('consumerToken');
    if (token) {
      this.$axios.get('/c/shop/getConsumer', { headers: { conAuth: token } }).then(({ data }) => {
        if (data.result !== 'fail') {
          this.$q.localStorage.set('consumer', data);
          this.consumer = data;
        } else {
          this.consumer = null;
          this.$q.localStorage.clear();
        }
      });
    }
  },
  methods: {
    toLogin () {
      this.$router.replace({ path: '/shop/login' });
    }
  },
  watch: {
    modelValue (val) {
      this.filter = val;
    },
    filter (val) {
      this.$emit('update:modelValue', val);
    }
  }
});
</script>
